﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleMvvmToolkit;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using BuyTicket.Service;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows;

namespace BuyTicket.ViewModels
{
    class LoginViewModel : ViewModelBase<LoginViewModel>
    {
        public LoginViewModel()
        {
            
        }

        event EventHandler<NotificationEventArgs> m_Loading;
        public event EventHandler<NotificationEventArgs> Loading
        {
            add
            {
                m_Loading += value;
            }
            remove
            {
                m_Loading -= value;
            }
        }

        event EventHandler<NotificationEventArgs> m_Loaded;
        public event EventHandler<NotificationEventArgs> Loaded
        {
            add
            {
                m_Loaded += value;
            }
            remove
            {
                m_Loaded -= value;
            }
        }


        event EventHandler<NotificationEventArgs> m_Logined;
        public event EventHandler<NotificationEventArgs> Logined
        {
            add
            {
                m_Logined += value;
            }
            remove
            {
                m_Logined -= value;
            }
        }

        event EventHandler<NotificationEventArgs<BitmapImage>> m_VerifyImageCompleted;
        public event EventHandler<NotificationEventArgs<BitmapImage>> VerifyImageCompleted
        {
            add
            {
                m_VerifyImageCompleted += value;
            }
            remove
            {
                m_VerifyImageCompleted -= value;
            }
        }

        ICommand m_LoginCommand = null;
        public ICommand LoginCommand
        {
            get
            {
                return m_LoginCommand ?? (m_LoginCommand = new DelegateCommand(Login));
            }
        }

        bool m_NotLogined = false;

        void Login()
        {
            if(string.IsNullOrEmpty(m_UserName)
                || string.IsNullOrEmpty(m_PassWord)
                || string.IsNullOrEmpty(m_VerifyCode))
            {
                MessageBox.Show("请填写完整的登录数据！", "错误提示",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                this.Async(new Func<object>(() =>
                {
                    string error;
                    bool logined = BuyTicketServiceV2.Login(m_UserName, m_PassWord, m_VerifyCode, out error);
                    if (!logined)
                    {
                        m_NotLogined = true;
                        if (!string.IsNullOrEmpty(error))
                        {
                            MessageBox.Show(error, "错误提示",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    return logined;
                }), new Action<object>(args =>
                {
                    bool logined = (bool)args;
                    if (logined)
                    {
                        if (m_Logined != null)
                        {
                            m_Logined(this, new NotificationEventArgs());
                        }
                    }
                    else
                    {
                        RefreshVerifyCode();  //注意：此过程中可能造成View中Loading状态不一致
                    }
                }));
            }
        }

        ICommand m_RefreshVerifyCodeCommand = null;
        public ICommand RefreshVerifyCodeCommand
        {
            get
            {
                return m_RefreshVerifyCodeCommand ?? (m_RefreshVerifyCodeCommand = new DelegateCommand(RefreshVerifyCode));
            }
        }

        void RefreshVerifyCode()
        {
            this.Async(new Func<object>(() =>
            {
                return BuyTicketServiceV2.GetVerifyImage();

                /* 过时
                var sm = BuyTicketService.GetVerifyImage();
                if (sm != null)
                {
                    try
                    {
                        using (FileStream fs = new FileStream(@"d:\\temp.png", FileMode.Create))
                        {
                            sm.CopyTo(fs);
                            fs.Close();
                        }

                        System.Drawing.Bitmap.FromStream(sm, true)
                          .Save(@"d:\\temp.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
       
                        BitmapImage image = new BitmapImage();
                        image.BeginInit();
                        image.StreamSource = sm;  //sm引用来自BackgroundWorker线程
                        image.EndInit();
                        return image;
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex);
                    }
                }
                return null;
                */ 
            }), new Action<object>((args) =>
            {
                BitmapImage image = null;
                Stream sm = args as Stream;
                if (sm != null)
                {
                    try
                    {
                        image = new BitmapImage();
                        image.BeginInit();
                        image.StreamSource = sm;  //sm引用来自BackgroundWorker线程
                        image.EndInit();
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex);
                    }
                }
                //通知到View
                if (m_VerifyImageCompleted != null)
                {
                    m_VerifyImageCompleted(this,
                        new NotificationEventArgs<BitmapImage>("", image));
                }
                this.VerifyCode = "";
                /*
                BitmapImage image = args as BitmapImage;
                if (image != null)
                {
                    if (m_VerifyImageCompleted != null)
                    {
                        m_VerifyImageCompleted(this, 
                            new NotificationEventArgs<BitmapImage>("", image));
                    }
                }*/
            }));

        }

        void Async(Func<object> func, Action<object> completed)
        {
            using (BackgroundWorker worker = new BackgroundWorker())
            {
                if (m_Loading != null)
                {
                    m_Loading(this, new NotificationEventArgs());
                }
                worker.DoWork += (sender, e) =>
                {
                    e.Result = func();
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    completed(e.Result);
                    if (m_NotLogined==false)   //登录失败时不通知Loaded事件
                    {
                        if (m_Loaded != null)
                        {
                            m_Loaded(this, new NotificationEventArgs());
                        }
                    }else
                       m_NotLogined = false; //重新标记
                };
                worker.RunWorkerAsync();
            }
        }

        string m_UserName;
        public string UserName
        {
            get
            {
                return m_UserName;
            }
            set
            {
                m_UserName = value;
                this.NotifyPropertyChanged(m => m.UserName);
            }
        }

        string m_PassWord;
        public string PassWord
        {
            get
            {
                return m_PassWord;
            }
            set
            {
                m_PassWord = value;
                this.NotifyPropertyChanged(m => m.PassWord);
            }
        }

        string m_VerifyCode;
        public string VerifyCode
        {
            get { return m_VerifyCode; }
            set
            {
                m_VerifyCode = value;
                this.NotifyPropertyChanged(m => m.VerifyCode);
            }
        }
    }
}
